from django.shortcuts import render, render_to_response
from django.http import FileResponse, HttpRequest, HttpResponse, JsonResponse
from config import Config
import os
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.gzip import gzip_page
import requests
import json


def pretty_request(request):
    headers = ''
    for header, value in request.META.items():
        if not header.startswith('HTTP'):
            continue
        header = '-'.join([h.capitalize() for h in header[5:].lower().split('_')])
        headers += '{}: {}\n'.format(header, value)

    return (
        '{method} HTTP/1.1\n'
        'Content-Length: {content_length}\n'
        'Content-Type: {content_type}\n'
        '{headers}\n\n'
        '{body}'
    ).format(
        method=request.method,
        content_length=request.META['CONTENT_LENGTH'],
        content_type=request.META['CONTENT_TYPE'],
        headers=headers,
        body=request.body,
    )


def transmission(request, *args):
    return render_to_response('transmission/index.html')


def src(request, *args):
    sending = open(os.path.join(Config.TEMPLATE, request.path.strip('/')), mode='rb')
    return FileResponse(sending)


@csrf_exempt
@gzip_page
def rpc(request, *args):
    headers = dict(request.headers)
    headers['Host'] = '127.0.0.1:9091'
    headers['Origin'] = 'http://127.0.0.1:9091'
    headers['Referer'] = 'http://127.0.0.1:9091/transmission/web/'
    rpc_json = json.loads(request.body.decode('utf-8'))

    rpc_response = requests.post("http://127.0.0.1:9091/transmission/rpc", headers=headers, json=rpc_json)

    '''if content_type == 'text/html;':
        response = HttpResponse(rpc_response.text)
        
    elif content_type == 'application/json;':
        print(rpc_response.headers)
        response = JsonResponse(rpc_response.json())
        response.__delitem__('Content-Encoding')'''

    response = HttpResponse(rpc_response.text)
    
    if rpc_response.status_code == 401:
        response = render_to_response('401.html')

    response.status_code = rpc_response.status_code
    
    for header in rpc_response.headers:
        response[header] = rpc_response.headers[header]
    response.__delitem__('Content-Encoding')
    response['Content-Length'] = str(len(response.content))

    return response
    